package com.peng.leetcode.tree;

import java.util.*;

/**
 * PathSum
 *
 * @author: lupeng6
 * @create: 2021/1/4 16:23
 */
public class PathSum {

    public static void main(String[] args) {
        Integer[] arr = {5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1};
        TreeNode treeNode = TreeMain.array2tree(arr);
        int i = new PathSum().pathSum(treeNode, 22);
        System.out.println(i);
    }

    private Deque<TreeNode> stack = new LinkedList<>();

    private int sum;

    public int pathSum(TreeNode root, int sum) {
        if (root == null && sum == 0) {
            return 1;
        }
        this.sum = sum;
        List<List<Integer>> result = new ArrayList<>();
        dfs(root, 0, result);
        return result.size();
    }

    void dfs(TreeNode node, int path, List<List<Integer>> result) {
        if (node == null) {
            return;
        }
        stack.offerLast(node);
        path += node.val;

        if (path == sum) {
            List<Integer> item = new ArrayList<>();
            stack.forEach(i -> item.add(i.val));
            result.add(item);
        }

        dfs(node.left, path, result);
        dfs(node.right, path, result);
        stack.pollLast();
    }
}
